﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Xml;

using System.Security.Cryptography;
using System.Text;
/// <summary>
/// Class1 的摘要说明
/// </summary>
public class wxapi_values
{

   
    private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
    /**
        * 设置某个字段的值
        * @param key 字段名
         * @param value 字段值
        */
    public void SetValue(string key, object value)
    {
        m_values[key] = value;
        
    }
    public void DelValue() {

        m_values.Clear();
    }
    /**
    * 根据字段名获取某个字段的值
    * @param key 字段名
     * @return key对应的字段值
    */
    public object GetValue(string key)
    {
        object o = null;
        m_values.TryGetValue(key, out o);
        return o;
    }
    public string set_orderby() { //字符串排序输出
        string param = "";
        foreach (KeyValuePair<string, object> s in m_values)
            param += s.Key + "=" + s.Value + "&";
        param = param.Trim(new char[] { '&' });
        return param;
    
    }
  
    public string GenerateCheckCode(int codeCount)//生成随机字符
    {
        string str = string.Empty;
        long num2 = DateTime.Now.Ticks;

        Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)));
        for (int i = 0; i < codeCount; i++)
        {
            char ch;
            int num = random.Next();
            if ((num % 2) == 0)
            {
                ch = (char)(0x30 + ((ushort)(num % 10)));
            }
            else
            {
                ch = (char)(0x41 + ((ushort)(num % 0x1a)));
            }
            str = str + ch.ToString();
        }
        return str;
    }

    private const string sContentType = "application/x-www-form-urlencoded";
  
    public  string PostMoths(string url, string param) //json数据传递
    {
        string strURL = url;
        System.Net.HttpWebRequest request;
        request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
        request.Method = "POST";
        request.ContentType = "application/json;charset=UTF-8";
        string paraUrlCoded = param;
        byte[] payload;
        payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
        request.ContentLength = payload.Length;
        Stream writer = request.GetRequestStream();
        writer.Write(payload, 0, payload.Length);
        writer.Close();
        System.Net.HttpWebResponse response;
        response = (System.Net.HttpWebResponse)request.GetResponse();
        System.IO.Stream s;
        s = response.GetResponseStream();
        string StrDate = "";
        string strValue = "";
        StreamReader Reader = new StreamReader(s, Encoding.UTF8);
        while ((StrDate = Reader.ReadLine()) != null)
        {
            strValue += StrDate;
        }
        return strValue;
    }
    /// <summary>
    /// 签名字符串
    /// </summary>
    /// <param name="prestr">需要签名的字符串</param>
    /// <param name="key">密钥</param>
    /// <param name="_input_charset">编码格式</param>
    /// <returns>签名结果</returns>
    public  string Sign(string prestr, string key, string _input_charset)
    {
        StringBuilder sb = new StringBuilder(32);

        prestr = prestr + key;

        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(prestr));
        for (int i = 0; i < t.Length; i++)
        {
            sb.Append(t[i].ToString("x").PadLeft(2, '0'));
        }

        return sb.ToString();
    }
    /// <summary>
    /// 签名字符串
    /// </summary>
    /// <param name="prestr">需要签名的字符串</param>
    /// <param name="key">密钥</param>
    /// <param name="_input_charset">编码格式</param>
    /// <returns>签名结果</returns>
    public string Sign_1(string prestr, string key, string _input_charset)
    {
        StringBuilder sb = new StringBuilder(32);

        prestr =key+ prestr + key;

        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(prestr));
        //for (int i = 0; i < t.Length; i++)
        //{
        //    sb.Append(t[i].ToString("X2"));

        //}
           // 第四步：把二进制转化为大写的十六进制
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < t.Length; i++)
    {
        result.Append(t[i].ToString("X2"));
    }
    return result.ToString();
    }
    /// <summary>
    /// 验证签名
    /// </summary>
    /// <param name="prestr">需要签名的字符串</param>
    /// <param name="sign">签名结果</param>
    /// <param name="key">密钥</param>
    /// <param name="_input_charset">编码格式</param>
    /// <returns>验证结果</returns>
    public  bool Verify(string prestr, string sign, string key, string _input_charset)
    {
        string mysign = Sign(prestr, key, _input_charset);
        if (mysign == sign)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
  

    /**
     * @将Dictionary转成xml
     * @return 经转换得到的xml串
     * @throws WxPayException
     **/
    public string ToXml()
    {
        //数据为空时不能转化为xml格式
        if (0 == m_values.Count)
        {
         
           
        }

        string xml = "<xml>";
        foreach (KeyValuePair<string, object> pair in m_values)
        {
            //字段值不能为null，会影响后续流程
            if (pair.Value == null)
            {
               
            }

            if (pair.Value.GetType() == typeof(int))
            {
                xml += "<" + pair.Key + ">" + pair.Value + "</" + pair.Key + ">";
            }
            else if (pair.Value.GetType() == typeof(string))
            {
                xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
            }
            else//除了string和int类型不能含有其他数据类型
            {
              
            }
        }
        xml += "</xml>";
        return xml;
    }
    /**
    * 生成时间戳，标准北京时间，时区为东八区，自1970年1月1日 0点0分0秒以来的秒数
     * @return 时间戳
    */
    public  string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    /*生成制定类型json   
  {
     无数据
         success: [
            {TableCount:false}             //是否有数据 
         ]
     有数据
         TableCount: [
            { title: 'member_title1', message: 'member_message1' },
            { title: 'member_title2', message: 'member_message2' }
         ]
        
     }
  */
    public  String HtmlJson(string TableCount, System.Data.DataSet ds)
    {

        string rowname = "";
        string rownumber = "";
        string datas = "{";
        string success = "";



            if (ds.Tables[0].Rows.Count > 0)
            {

                if (datas != "{")
                {

                    datas += string.Format(",\"{0}\":[",  TableCount);
                }
                else
                {



                    datas += string.Format("\"{0}\":[",  TableCount);
                }
                int t = ds.Tables[0].Columns.Count;
                for (int row = 0; row < ds.Tables[0].Rows.Count; row++)
                {

                    for (int Column = 0; Column < t; Column++)
                    {

                        rowname = ds.Tables[0].Columns[Column].ToString();
                        rownumber = ds.Tables[0].Rows[row][rowname].ToString();

                        if (Column == 0)
                        {
                            if (row == 0)
                            {
                                datas += "{";
                            }
                            else
                            {
                                datas += ",{";
                            }

                            datas += string.Format("\"{0}\":\"{1}\"", rowname, rownumber);
                            if (t == Column + 1)
                            {
                                datas += "}";
                            }
                        }
                        else
                        {
                            datas += string.Format(",\"{0}\":\"{1}\"", rowname, rownumber);
                            if (t == Column + 1)
                            {
                                datas += "}";
                            }
                        }



                    }


                }
                datas += "]";
            }
            else
            {


                    success += string.Format("\"{0}\":\"false\"", TableCount);

                
            }

        
        if (datas == "{")
        {

            datas += "\"success\":[{";
            datas += success;
            datas += "}]";
            
          
        }
        datas += "}";
        return datas;

    }
   
    public wxapi_values()
	{

		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
}